/**
 * s_sensor.c
 * sensor source for TrayInfo.
 * Sensor support added by Laszlo Ashin <kodest@gmail.com>
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "trayinfo.h"

static char *sensor_config;

static int
sensor_write(struct timeval *now, int fd)
{
	char *s = sensor_config;
	int n = 0;

	if (!s) return 0;
	for (;;) {
		char buf[64], *t, *p, *q[3], buf2[96];
		int i, j;
		FILE *f;
		double val;

		while (*s < 33) {
			if (!*s) return n;
			++s;
		}
		i = sizeof(buf) - 1;
		j = 0;
		q[j++] = p = buf;
		for (t = s; *t > 32; ++t)
			if (i > 0) {
				*p++ = *t;
				--i;
				if (*t == '#' && j < 3) {
					q[j++] = p;
					p[-1] = '\0';
				}
			}

		*p = '\0';
		s = t;
		if (j != 3) continue;
		i = snprintf(
			buf2, sizeof(buf2) - 1,
			"/sys/class/hwmon/%s_input",
			q[1]
		);
		if (i > sizeof(buf2) - 1) continue;
		f = fopen(buf2, "r");
		if (!f) continue;
		i = fscanf(f, "%lf", &val);
		fclose(f);
		if (i != 1) continue;
		if (n) put_separator();
		printf("%s%2.1f%s", q[0], val / 1000.0f, q[2]);
		++n;
	}
	return n;
}

static void
sensor_init(void)
{
	sensor_config = NULL;
}

static void
sensor_done(void)
{
	if (sensor_config) free(sensor_config);
	sensor_config = NULL;
}

static int
sensor_cfg_sensors(const char *s)
{
	if (sensor_config) free(sensor_config);
	sensor_config = strdup(s);
	return 0;
}

void
regsrc_sensor(src_t *src)
{
	src->name = "sensor";
	src->init = sensor_init;
	src->done = sensor_done;
	src->write = sensor_write;

	cfg_add_handler("sensors", sensor_cfg_sensors);
}
